<?php
namespace app\jobs;

use app\config\Constants;
use app\models\Goods;
use app\models\GoodsAttribute;
use app\models\GoodsOrder;

class CountJob {

    private static $handle_type = [Constants::ORDER_WAIT,Constants::ORDER_CANCEL];

    public function execute($queue,$job){
        if($job['msg_type'] != Constants::MSG_TYPE_ORDER){
            return true;
        }
        if(!in_array($job['event_type'],self::$handle_type)){
            return true;
        }

        $order = GoodsOrder::findOne(['order_no'=>$job['data']['order_no']]);
        if(!$order){
            return false;
        }

        $result = false;
        if($job['event_type'] == Constants::ORDER_WAIT){
            $result = $this->wait($order);
        }
        if($job['event_type'] == Constants::ORDER_CANCEL){
            $result = $this->cancel($order);
        }
        return $result;
    }

    //减库存
    public function wait(GoodsOrder $order){
        foreach($order->getGoodsItem() as $k=>$v){
            //属性
            if(!isset($v['attr_ids'])){
                $goods = Goods::findOne(['merchant_id'=>$order->merchant_id,'goods_id'=>$v['goods_id']]);
                if(!$goods){
                    continue;
                }
                $goods->count -= $v['new_count'];
                $goods->update();
            }else{
                foreach($v['attr_ids'] as $kk=>$vv){
                    $attr = GoodsAttribute::findOne(['goods_id'=>$v['goods_id'],'goods_attr_id'=>$vv]);
                    if(!$attr){
                        continue;
                    }
                    $attr->count -= $v['new_count'];
                    $attr->update();
                }
            }
        }
        return true;
    }

    //加库存
    public function cancel(GoodsOrder $order){
        foreach($order->getGoodsItem() as $k=>$v){
            //属性
            if(!isset($v['attr_ids'])){
                $goods = Goods::findOne(['merchant_id'=>$order->merchant_id,'goods_id'=>$v['goods_id']]);
                if(!$goods){
                    continue;
                }
                $goods->count += $v['new_count'];
                $goods->update();
            }else{
                foreach($v['attr_ids'] as $kk=>$vv){
                    $attr = GoodsAttribute::findOne(['goods_id'=>$v['goods_id'],'goods_attr_id'=>$vv]);
                    if(!$attr){
                        continue;
                    }
                    $attr->count += $v['new_count'];
                    $attr->update();
                }
            }
        }
        return true;
    }
}